package com.pet.serve.repository;

import com.pet.serve.entity.Shopcar;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Repository
public interface ShopcarRepository extends JpaRepository<Shopcar, Long> {

    // 查找购物车中的商品
    List<Shopcar> findByUsername(String username);

    // 根据用户名和商品ID或宠物ID查询购物车中的商品
    @Query("SELECT s FROM Shopcar s WHERE s.username = :username AND (s.goodid = :goodid OR s.petid = :petid)")
    Shopcar findByUsernameAndItem(@Param("username") String username, @Param("goodid") Long goodid, @Param("petid") Long petid);

    // 删除购物车中的商品
    void deleteByUsername(String username);

    Optional<Shopcar> findByUsernameAndGoodidAndPetid(String username, Long goodid, Long petid);

    // 更新购物车中的商品数量和总价
    @Query("UPDATE Shopcar s SET s.num = :num, s.totalPrice = :totalPrice WHERE s.shopcarid = :id")
    void updateShopcarItem(@Param("id") Long id, @Param("num") Integer num, @Param("totalPrice") BigDecimal totalPrice);

    @Query("SELECT s FROM Shopcar s JOIN s.goods g WHERE s.username = :username AND g.status = :status")
    List<Shopcar> findByUsernameAndGoodsStatus(@Param("username") String username, @Param("status") String status);

    @Query("SELECT s FROM Shopcar s JOIN s.pets p WHERE s.username = :username AND p.status = :status")
    List<Shopcar> findByUsernameAndPetsStatus(@Param("username") String username, @Param("status") String status);
}
